<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 实时数据获取接口
 * 尊重劳动成果是一种美德
 */

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

// 加载配置和类文件
require_once __DIR__ . '/../classes/H3OpenApiClient.php';

try {
    // 读取配置文件
    $config = require __DIR__ . '/../config.php';
    
    // 获取请求参数
    $schemaCode = $_GET['schema_code'] ?? '';
    $tokenSecret = $_GET['token'] ?? '';
    $page = max(1, (int)($_GET['page'] ?? 1));
    $size = min(max(1, (int)($_GET['size'] ?? 100)), 500); // 限制最大500条
    $keyword = $_GET['keyword'] ?? '';
    
    // 验证 schema_code
    if (empty($schemaCode)) {
        echo json_encode([
            'success' => false,
            'message' => '缺少schema_code参数'
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 验证 token
    if (empty($tokenSecret)) {
        echo json_encode([
            'success' => false,
            'message' => '缺少token参数'
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 从配置中查找对应的表单并验证token
    $schemas = $config['schemas'] ?? [];
    $matchedSchema = null;
    
    foreach ($schemas as $schemaKey => $schemaData) {
        if ($schemaData['schema_code'] === $schemaCode) {
            // 验证token
            if (isset($schemaData['token_secret']) && $schemaData['token_secret'] === $tokenSecret) {
                $matchedSchema = $schemaData;
                break;
            }
        }
    }
    
    if (!$matchedSchema) {
        echo json_encode([
            'success' => false,
            'message' => 'Token验证失败或表单不存在'
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 初始化氚云API客户端
    $apiConfig = [
        'baseUrl' => $config['baseUrl'],
        'appCode' => $config['appCode'],
        'appSecret' => $config['appSecret'],
        'debug' => $config['debug'] ?? false
    ];
    
    $client = new H3OpenApiClient($apiConfig);
    
    // 计算分页参数
    $fromRowNum = ($page - 1) * $size;
    $toRowNum = $fromRowNum + $size;
    
    // 构建查询条件
    $matcher = [
        'Type' => 'And',
        'Matchers' => []
    ];
    
    // 如果有关键词搜索，添加搜索条件
    if (!empty($keyword)) {
        // 添加多字段模糊搜索
        $matcher['Matchers'][] = [
            'Type' => 'Or',
            'Matchers' => [
                [
                    'Type' => 'ItemMatcher',
                    'ItemName' => 'Name',
                    'Operator' => 'Contains',
                    'Value' => $keyword
                ],
                [
                    'Type' => 'ItemMatcher',
                    'ItemName' => 'F0000001', // 货号
                    'Operator' => 'Contains',
                    'Value' => $keyword
                ],
                [
                    'Type' => 'ItemMatcher',
                    'ItemName' => 'F0000002', // 其他常用字段
                    'Operator' => 'Contains',
                    'Value' => $keyword
                ]
            ]
        ];
    }
    
    // 构建过滤条件
    $filter = [
        'FromRowNum' => $fromRowNum,
        'ToRowNum' => $toRowNum,
        'RequireCount' => true,
        'ReturnItems' => [], // 返回所有字段
        'SortByCollection' => [
            [
                'ItemName' => 'CreatedTime',
                'Direction' => 'Descending' // 按创建时间倒序
            ]
        ],
        'Matcher' => $matcher
    ];
    
    // 调用API获取数据
    $bizObjects = $client->loadBizObjects($schemaCode, $filter);
    
    // 获取总记录数（如果API返回）
    $totalCount = count($bizObjects); // 实际返回的记录数
    
    // 处理数据，转换为标准格式
    $formattedData = [];
    foreach ($bizObjects as $obj) {
        $formattedData[] = $obj;
    }
    
    // 返回结果
    echo json_encode([
        'success' => true,
        'data' => $formattedData,
        'pagination' => [
            'page' => $page,
            'size' => $size,
            'total' => $totalCount,
            'has_more' => count($formattedData) >= $size
        ],
        'schema' => [
            'code' => $schemaCode,
            'name' => $matchedSchema['schema_name'] ?? ''
        ]
    ], JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    // 记录错误日志（如果开启调试模式）
    if (isset($config['debug']) && $config['debug']) {
        // 日志已禁用
        // $logDir = __DIR__ . '/../logs/api';
        // if (!is_dir($logDir)) {
        //     @mkdir($logDir, 0755, true);
        // }
        // $logFile = $logDir . '/get_data_error.log';
        // $timestamp = date('Y-m-d H:i:s');
        // $errorMsg = "[{$timestamp}] Error: {$e->getMessage()}\n";
        // $errorMsg .= "Request: " . json_encode($_GET) . "\n";
        // $errorMsg .= "Stack trace: {$e->getTraceAsString()}\n\n";
        // @file_put_contents($logFile, $errorMsg, FILE_APPEND | LOCK_EX);
    }
    
    echo json_encode([
        'success' => false,
        'message' => '数据获取失败: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
